/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-30 16:57:55
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-30 14:22:27
 * @FilePath: \keep_motion_api\models\community.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 社区帖子模型
const communityPostSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  content: String,
  images: [String],
  likes: [{
    type: Schema.Types.ObjectId, 
    ref: 'User'
  }],
  comments: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    content: String,
    time: { type: Date, default: Date.now }
  }],
  create_time: { type: Date, default: Date.now },
  is_top: { type: Boolean, default: false },
  topic: String,
  related_activity: {
    type: Schema.Types.ObjectId,
    ref: 'Activity'
  },
  related_course: {
    type: Schema.Types.ObjectId,
    ref: 'Course'
  }
});

communityPostSchema.statics.getPosts = async function(user_name, user_id, topic, activity_id, related_activity, course_id, related_course, offset = 0, limit = 10) {
  try {
    const query = {};
    if (user_name){
      const { User } = require('../user');
      const parentQuery = { name: { $regex: escapeRegex(user_name), $options: 'i' } };
      const rows = await User.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      query.user_id = {$in: rows.map(item => item._id) };
    }
    if (related_activity) {
      const { Activity } = require('../sport');
      const parentQuery = { title: { $regex: escapeRegex(related_activity), $options: 'i' } };
      const rows = await Activity.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      query.related_activity = { $in: rows.map(item => item._id) };
    }
    if (related_course) {
      const { Course } = require('../course');
      const parentQuery = { title: { $regex: escapeRegex(related_course), $options: 'i' } };
      const rows = await Course.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      query.related_course = { $in: rows.map(item => item._id) };
    }
    if (user_id) query.user_id = user_id;
    if (topic) {
      const escapedTopic = escapeRegex(topic);
      query.topic = { $regex: escapedTopic, $options: 'i' };
    }
    if (activity_id) query.related_activity = activity_id;
    if (course_id) query.related_course = course_id;

    const [result] = await this.aggregate([
        // 1. 匹配查询条件
        { $match: query },
        
        // 2. 关联查询user数据
        { $lookup: {
          from: 'users', // 关联的集合名
          localField: 'user_id', // 本地关联字段
          foreignField: '_id', // 关联集合的匹配字段
          as: 'user_info' // 存储关联结果的字段名
        }},
        
        // 3. 关联查询likes数据
        { $lookup: {
          from: 'users', // 关联的集合名
          localField: 'likes', // 本地关联字段
          foreignField: '_id', // 关联集合的匹配字段
          as: 'likes_info' // 存储关联结果的字段名
        }},
        
        // 4. 关联查询comments数据
        { $lookup: {
          from: 'users', // 关联的集合名
          localField: 'comments.user_id', // 本地关联字段
          foreignField: '_id', // 关联集合的匹配字段
          as: 'comments_info' // 存储关联结果的字段名
        }},
        // 5. 关联查询related_activity数据
        {
          $lookup: {
            from: 'activities', // 关联的集合名
            localField: 'related_activity', // 本地关联字段
            foreignField: '_id', // 关联集合的匹配字段
            as: 'related_activity_info' // 存储关联结果的字段名
          }
        },
        // 6. 关联查询related_course数据
        {
          $lookup: {
            from: 'courses', // 关联的集合名
            localField: 'related_course', // 本地关联字段
            foreignField: '_id', // 关联集合的匹配字段
            as: 'related_course_info' // 存储关联结果的字段名
          }
        },

        { $unwind: '$user_info' },   
        { $unwind: '$related_activity_info' },
        { $unwind: '$related_course_info' },
        // 4. 统计总数并添加到每个文档中（用于后续分页后仍能获取总条数）
        { $facet: {
          metadata: [{
            $count: 'total' // 统计符合条件的总文档数
          }],
          data: [
            // 投影需要的字段
            { $project: {
              _id: 1,
              user_id: 1,
              user_name: '$user_info.name',
              avatar: '$user_info.avatar',
              content: 1,
              images: 1,
              comments: 1,
              create_time: 1,
              is_top: 1,
              topic: 1,
              related_activity: 1,
              related_activity_title: '$related_activity_info.title',
              related_course: 1,
              related_course_title: '$related_course_info.title',
              likes_count: { $size: '$likes_info' },
              likes_info: {
                $map: {
                  input: '$likes_info',
                  as: 'like',
                  in: {
                    user_id: '$$like._id',
                    user_name: '$$like.name',
                    avatar: '$$like.avatar'
                  }
                }
              },
              comments_count: { $size: '$comments_info' },
              comments_info: {
                $map: {
                  input: '$comments_info',
                  as: 'comment',
                  in: {
                    user_id: '$$comment._id',
                    user_name: '$$comment.name',
                    content: '$$comment.content',
                    time: '$$comment.time',
                    avatar: '$$comment.avatar'
                  }
                }
              }
            }},
            // 分页
            { $skip: Number(offset) },
            { $limit: Number(limit) }
          ]
        }},
        
        // 5. 整合结果
        { $unwind: '$metadata' },
        { $project: {
          rows: '$data',
          total: '$metadata.total'
        }}
      ]);
      // 处理没有结果的情况
    if (!result || !result.rows) {
      return { rows: [], total: 0 };
    }
    return result;
  } catch (error) {
    console.error('获取社区帖子失败:', error);
    throw new Error('获取社区帖子失败');
  }
}
communityPostSchema.statics.deletePost = async function(id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    console.error('删除社区帖子失败:', error);
    throw new Error('删除社区帖子失败');
  }
}
communityPostSchema.statics.pinPost = async function(id, is_top) {
  try {
    return await this.findByIdAndUpdate(id, { is_top }, { new: true });
  } catch (error) {
    console.error('置顶/取消置顶社区帖子失败:', error);
    throw new Error('置顶/取消置顶社区帖子失败');
  }
}
communityPostSchema.statics.deleteComment = async function(id, commentId) {
  try {
    return await this.findByIdAndUpdate(id, { $pull: { comments: { _id: commentId } } }, { new: true });
  } catch (error) {
    console.error('删除社区帖子评论失败:', error);
    throw new Error('删除社区帖子评论失败');  
  }
}
module.exports = mongoose.model('CommunityPost', communityPostSchema);
